package com.motu.monstercity.server.login.handler;

import com.motu.monstercity.module.common.utility.CmdConstant;
import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.module.common.utility.EventBusConstant;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.Tool;
import com.motu.vertx.module.utility.webtool.BaseWebHandler;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// M币网站跟游戏进程进行交互，统一放在这里
public class MotumallManager extends BaseWebHandler {
    private final static Logger logger = LoggerFactory.getLogger(MotumallManager.class);

    // 校验ip是否在白名单，true 是白名单
    private static boolean checkWhiteIp(String ip) {
        return true;
    }

    public static void doGet(RoutingContext routingContext) {
        String ip = BaseWebHandler.getClientIp(routingContext);
        String path = routingContext.request().path();
        logger.info("###Motumall doGet ip:" + ip + " path:" + path);
        if (checkWhiteIp(ip)) {
            if (path.contains("/rolelist")) {
                getRoleList(routingContext);// 下发区服角色列表 motumall  魔兔网页充值用的接口
            } else  if (path.contains("/roleinfo")) {
                getRoleInfo(routingContext);// 下发角色信息 motumall  魔兔网页充值用的接口
            } else {
                routingContext.fail(404); // 未定义的路径
            }
        } else {
            logger.error("###MotumallManager error ip:" + ip);
            routingContext.fail(404); // 未定义的路径
        }
    }

    public static void doPost(RoutingContext routingContext) {
        HttpServerRequest request = routingContext.request();
        JsonObject jsonObject = routingContext.body().asJsonObject();
        String ip = BaseWebHandler.getClientIp(routingContext);
        String path = routingContext.request().path();
        logger.info("###Motumall doPost ip:" + ip + " path:" + path + " json:" + jsonObject);
        if (checkWhiteIp(ip)) {
            if (path.contains("/sendmail")) {
                sendMail(routingContext, jsonObject);// 发送奖励邮件的接口,邮件标题,邮件内容,奖励内容，获得日志
            } else {
                routingContext.fail(404); // 未定义的路径
            }
        } else {
            logger.error("###MotumallManager error ip:" + ip);
            routingContext.fail(404); // 未定义的路径
        }
    }

    /**
     * 获取角色列表
     * @param routingContext
     */
    private static void getRoleList(RoutingContext routingContext) {
        HttpServerRequest request = routingContext.request();
        HttpServerResponse response = routingContext.response();

        String accid = request.getParam("accid");
        String acctype = request.getParam("acctype");
        String sql = "SELECT a.id, a.user_name as username, a.vip, a.level, a.server_id as serverid, a.login_time as logintime FROM user_info a left JOIN user_ext_info b ON a.id = b.id WHERE b.account_id = ? AND b.account_type = ? order by a.server_id asc;";
        JsonArray params = new JsonArray();
        params.add(accid);
        params.add(acctype);
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params, res->{
            JsonObject result = new JsonObject();
            if (res.succeeded()) {
                result.put("roleList", res.result());
                response.end(result.toString());
            }
            sendHttpResponse(routingContext.response(), result);
        });
    }

    /**
     * 获取角色信息,最高vip,最低vip,最后一次登录时间
     * @param routingContext
     */
    private static void getRoleInfo(RoutingContext routingContext) {
        HttpServerRequest request = routingContext.request();
        HttpServerResponse response = routingContext.response();

        String accid = request.getParam("accid");
        String acctype = request.getParam("acctype");
        String sql = "SELECT IFNULL(max( a.vip ),0) AS vip, IFNULL(max( login_time ),0) logintime  from user_info a,user_ext_info b where a.id=b.id and b.account_id=?;";
        JsonArray params = new JsonArray();
        params.add(accid);
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql, params, res->{
            JsonObject result = new JsonObject();
            if (res.succeeded() && res.result().size() == 1) {
                result.put("roleInfo", res.result().getJsonObject(0));
                response.end(result.toString());
            }
            sendHttpResponse(routingContext.response(), result);
        });
    }

    /**
     * 发送奖励邮件的通用接口,带邮件标题,邮件内容,邮件附件
     * @param routingContext
     */
    private static void sendMail(RoutingContext routingContext, JsonObject jsonObject) {
        HttpServerResponse response = routingContext.response();
        try {
            logger.info("###MotumallManager :" + jsonObject);
            long userId = jsonObject.getLong("userid");
            String itemStr = jsonObject.getString("item");
            int titleId = jsonObject.getInteger("titleid");
            int contentId = jsonObject.getInteger("contentid");
            int logType = jsonObject.getInteger("logtype");

            JsonObject message = new JsonObject();
            message.put("cmd", CmdConstant.CMD_MOTUMALL_SEND_MAIL_REWARD);
            JsonObject obj = new JsonObject();
            obj.put("userId", userId);
            obj.put("reward", itemStr);//
            obj.put("title", titleId);//
            obj.put("content", contentId);//
            obj.put("logType", logType);//
            message.put("data", obj);
            String ebName = EventBusConstant.getAddress(EventBusConstant.GAME_CUSTOM_LOGIC);
            EventBus eventBus = MainService.getVertx().eventBus();
            logger.info("###MotumallManager sendMail userid:" + userId + " title:" + titleId + " reward:" + itemStr + " ebname:" + ebName);
            eventBus.request(ebName, message, r -> {
                if (r.succeeded()) {
                    logger.info("###MotumallManager sendMail success userid:" + userId + " title:" + titleId + " reward:" + itemStr);
                    sendHttpResponse(routingContext.response(), new JsonObject());
                } else {
                    logger.error("###MotumallManager sendMail fail userid:" + userId + " title:" + titleId + " reward:" + itemStr + " exception:" + Tool.getException(r.cause()));
                    sendHttpResponseError(response, "");
                }
            });
        } catch (Exception e) {
            logger.error("###MotumallManage error:" + Tool.getException(e));
            sendHttpResponseError(response, "");
        }
    }
}
